﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QFlow.Data;

namespace QFlow.Windows.Forms
{
    public partial class ProductAdjustment : Utils.BaseForm
    {
        PurchaseOrder _POrder;
        SaleOrder _SOrder;

        public ProductAdjustment(QFlowDbContext context)
            : base(context)
        {
            InitializeComponent();
            cmbProduct.DataSource = this.Context.Products.Where(product => !product.IsNonStockable).ToArray();

            _POrder = new PurchaseOrder();
            _SOrder = new SaleOrder();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (cmbProduct.SelectedIndex != -1)
            {
                if (superValidator1.Validate())
                {
                    Product product = cmbProduct.SelectedItem as Product;

                    bool adjusted = false;
                    foreach (var item in _POrder.PurchaseItems)
                    {
                        if (item.ProductID == product.ProductID)
                            adjusted = true;
                    }
                    foreach (var item in _SOrder.SaleItems)
                    {
                        if (item.ProductID == product.ProductID)
                            adjusted = true;
                    }
                    if (adjusted)
                    {
                        MessageBox.Show(QFlow.Windows.Properties.Resources.MBAlreadyAdjusted, QFlow.Windows.Properties.Resources.MBErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    }
                    else
                    {
                        double currentQuantity = double.Parse(txtCurrentQantity.Text);
                        double newQuantity = double.Parse(txtNewQuantity.Text);
                        #warning this might crash
                        //User currentUser = this.Context.Users.Single(user => user.UserID == (QFlow.Core.Authentication.CurrentUser as user).UserID);
                        User currentUser = QFlow.Core.Authentication.CurrentUser as User;

                        if (newQuantity > currentQuantity)
                        {
                            PurchaseItem item = new PurchaseItem();
                            item.Product = product;
                            item.Quantity = newQuantity - currentQuantity;
                            item.User = currentUser;
                            item.UnitPrice = product.StockableProduct.PurchaseUnitPrice;
                            item.TaxesPercent = product.StockableProduct.TaxesPercent;
                            item.DiscountPercent = 0;
                            item.Timestamp = DateTime.Now;
                            item.ItemType = this.Context.ItemTypes.GetReceivedType();

                            _POrder.PurchaseItems.Add(item);
                            item.Product.StockableProduct.CurrentQuantity = newQuantity;
                        }
                        else
                        {
                            SaleItem item = new SaleItem();
                            item.StockableProduct = product.StockableProduct;
                            item.Quantity = currentQuantity - newQuantity;
                            item.User = currentUser;
                            item.UnitPrice = product.StockableProduct.SalesUnitPrice;
                            item.TaxesPercent = product.StockableProduct.TaxesPercent;
                            item.DiscountPercent = 0;
                            item.Timestamp = DateTime.Now;

                            #warning take care of the type here
                            item.ItemType = this.Context.ItemTypes.GetReceivedType();

                            _SOrder.SaleItems.Add(item);
                            item.StockableProduct.CurrentQuantity = newQuantity;
                        }
                        txtCurrentQantity.Text = newQuantity.ToString("F");
                        UpdateItemsGrid();

                        cmbProduct.SelectedIndex = -1;
                        txtCurrentQantity.Text = string.Empty;
                        txtNewQuantity.Text = string.Empty;
                    }
                }
            }
        }

        private void UpdateItemsGrid()
        {
            var purchased = from pItem in _POrder.PurchaseItems
                            select new
                            {
                                Product = pItem.Product.Name,
                                CurrentQuantity = pItem.Product.StockableProduct.CurrentQuantity - pItem.Quantity,
                                NewQuantity = pItem.Product.StockableProduct.CurrentQuantity
                            };

            var sold = from sItem in _SOrder.SaleItems
                       select new
                       {
                           Product = sItem.StockableProduct.Product.Name,
                           CurrentQuantity = sItem.StockableProduct.CurrentQuantity + sItem.Quantity,
                           NewQuantity = sItem.StockableProduct.CurrentQuantity
                       };
            var result = purchased.Union(sold);
            gvItems.DataSource = result.ToList();
        }

        private void cmbProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbProduct.SelectedIndex > -1)
            {
                Product product = cmbProduct.SelectedItem as Product;
                txtCurrentQantity.Text = product.StockableProduct.CurrentQuantity.ToString("F");
                txtNewQuantity.Text = string.Empty;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (_POrder.PurchaseItems.Count > 0)
                {
                    #warning discuss later
                    _POrder.PaymentMethod = this.Context.PaymentMethods.First();
                    _POrder.Date = DateTime.Now;
                    _POrder.DiscountPercent = 0;
                    #warning discuss later2
                    _POrder.Vendor = this.Context.Vendors.First();
                    _POrder.OrderStatus = this.Context.OrderStatus.GetAdjustedStatus();
                }

                if (_SOrder.SaleItems.Count > 0)
                {
                    #warning discuss later
                    _POrder.PaymentMethod = this.Context.PaymentMethods.First();
                    _SOrder.Date = DateTime.Now;
                    _SOrder.DiscountPercent = 0;
                    #warning discuss later2
                    _SOrder.Customer = this.Context.Customers.First();
                    _SOrder.OrderStatus = this.Context.OrderStatus.GetAdjustedStatus();
                }
                this.Context.SubmitChanges();
                PostSave();
            }
            catch
            {
                MessageBox.Show(QFlow.Windows.Properties.Resources.MBCantSaveChanges, QFlow.Windows.Properties.Resources.MBErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }

        private void PostSave()
        {
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ProductAdjustment_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Context.DiscardChanges();
        }
    }
}
